<template>
    <div class="user-info-head" @click="editCropper()">
        <img v-if="url" :src="baseUrl + url" :title="title" class="w-[300px] h-[150px] block" alt=""/>
        <div v-else class="w-[300px] h-[150px] block el-upload el-upload--picture-card" >
            <svg-icon icon-class="el-Plus"/>
        </div>
        <el-dialog :title="title" v-model="open" width="1200px" append-to-body @opened="modalOpened" @close="closeDialog">
            <el-row>
                <el-col :xs="24" :md="12" :style="{ height: '350px' }">
                    <vue-cropper
                            ref="cropper"
                            :img="options.img"
                            :outputSize="options.outputSize"
                            :outputType="options.outputType"
                            :info="options.info"
                            :infoTrue="options.infoTrue"
                            :canScale="options.canScale"
                            :autoCrop="options.autoCrop"
                            :autoCropWidth="options.autoCropWidth"
                            :autoCropHeight="options.autoCropHeight"
                            :fixed="options.fixed"
                            :fixedNumber="options.fixedNumber"
                            :full="options.full"
                            :fixedBox="options.fixedBox"
                            :canMove="options.canMove"
                            :canMoveBox="options.canMoveBox"
                            :original="options.original"
                            :centerBox="options.centerBox"
                            :height="options.height"
                            :maxImgSize="options.maxImgSize"
                            :enlarge="options.enlarge"
                            :mode="options.mode"
                            @realTime="realTime"
                            v-if="visible"
                    />
                </el-col>
                <el-col :xs="24" :md="12" :style="{ height: '350px' }">
                    <div class="preview" :style="{'width': options.previews.w + 'px', 'height': options.previews.h + 'px',  'overflow': 'hidden',
							'margin': '5px'}">
                        <img v-if="options.previews.url" :src="options.previews.url" :style="options.previews.img" alt=""/>
                    </div>
                </el-col>
            </el-row>
            <br/>
            <el-row>
                <el-col :lg="2" :md="2">
                    <el-upload
                            action="#"
                            :http-request="requestUpload"
                            :show-file-list="false"
                            :before-upload="beforeUpload"
                    >
                        <el-button>
                            选择
                            <svg-icon icon-class="el-Upload" class="el-icon--right"/>
                        </el-button>
                    </el-upload>
                </el-col>
                <el-col :lg="{ span: 1, offset: 2 }" :md="2">
                    <el-button icon="Plus" @click="changeScale(1)"></el-button>
                </el-col>
                <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                    <el-button icon="Minus" @click="changeScale(-1)"></el-button>
                </el-col>
                <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                    <el-button icon="RefreshLeft" @click="rotateLeft()"></el-button>
                </el-col>
                <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                    <el-button icon="RefreshRight" @click="rotateRight()"></el-button>
                </el-col>
                <el-col :lg="{ span: 2, offset: 6 }" :md="2">
                    <el-button type="primary" @click="uploadImg()">提 交</el-button>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script setup>
import "vue-cropper/dist/index.css";
import {VueCropper} from "vue-cropper";
import {upload} from "@/api/system/oss.js";
import {defineModel} from 'vue'
import SvgIcon from "@/components/SvgIcon/index.vue";
const {msgSuccess, msgError} = useModal()
const baseUrl = import.meta.env.VITE_APP_BASE_API

const props = defineProps({
    //modelValue: Number,
    title: {
        type: String,
        default: '裁切上传'
    },
    fixedNumber: {
        type: Array,
        default: [1.5, 1]
    },
})
const modelValue = defineModel('modelValue')
const url = defineModel('url')

const cropper = ref()
const open = ref(false);
const visible = ref(false);

//图片裁剪数据
const options = reactive({
    img: url.value,             //裁剪图片的地址
    outputSize: 1,       //裁剪生成图片的质量(可选0.1 - 1)
    outputType: 'png',  //裁剪生成图片的格式（jpeg || png || webp）
    info: true,          //图片大小信息
    canScale: true,      //图片是否允许滚轮缩放
    autoCrop: true,      //是否默认生成截图框
    //autoCropWidth: 420,  //默认生成截图框宽度
    //autoCropHeight: 350, //默认生成截图框高度
    fixed: true,         //是否开启截图框宽高固定比例
    fixedNumber: props.fixedNumber, //截图框的宽高比例
    full: true,         //false按原比例裁切图片，不失真
    fixedBox: false,      //固定截图框大小，不允许改变
    canMove: false,      //上传图片是否可以移动
    canMoveBox: true,    //截图框能否拖动
    original: false,     //上传图片按照原始比例渲染
    centerBox: false,    //截图框是否被限制在图片里面
    height: true,        //是否按照设备的dpr 输出等比例图片
    infoTrue: true,     //true为展示真实输出图片宽高，false展示看到的截图框宽高
    maxImgSize: 3000,    //限制图片最大宽度和高度
    enlarge: 1,          //图片根据截图框输出比例倍数
    mode: 'cover',  //图片默认渲染方式
    previews: {
        url: '',
        img: {}
    } //预览数据
});

/**
 * 打开裁切框
 */
function editCropper() {
    open.value = true;
}

/** 打开弹出层结束时的回调 */
function modalOpened() {
    visible.value = true;
}

/** 覆盖默认上传行为 */
function requestUpload() {
}

/** 向左旋转 */
function rotateLeft() {
    cropper.value.rotateLeft();
}

/** 向右旋转 */
function rotateRight() {
    cropper.value.rotateRight();
}

/** 图片缩放 */
function changeScale(num) {
    num = num || 1;
    cropper.value.changeScale(num);
}

/** 上传预处理 */
function beforeUpload(file) {
    if (file.type.indexOf("image/") === -1) {
        msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
            options.img = reader.result;
            options.filename = file.name;
        };
    }
}

/** 上传图片 */
function uploadImg() {
    cropper.value.getCropBlob(data => {
        console.log(data)
        let formData = new FormData();
        formData.append("file", data, options.filename);
        upload(formData).then(res => {
            //options.img = res.data.url;
            open.value = false;
            visible.value = false;
            msgSuccess("上传成功");
            modelValue.value = res.data.ossId
            url.value = res.data.url
        });
    });
}

/** 实时预览 */
const realTime = data => options.previews = data


/** 关闭窗口 */
function closeDialog() {
    //options.img = userStore.avatar;
    options.visible = false;
}
</script>

<style lang='scss' scoped>

.preview {
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    //width: 430px;
    //height: 350px;
    //border-radius: 10px;
    //box-shadow: 0 0 4px #ccc;
    //overflow: hidden;
}

.user-info-head {
    position: relative;

}

.user-info-head:hover:after {
    content: "+";
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    color: #eee;
    background: rgba(0, 0, 0, 0.5);
    font-size: 24px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
}

.noFile {
    //border: ;
}

</style>
